<template>
    <div class="map" :style="{ width: mapWidth, height: mapHeight }">
        正在加载数据 ...
    </div>
</template>
<script>
import remoteLoad from './remoteLoad'

export default {
    name: 'a-map',
    props: {
        mapWidth: {
            type: String,
            default: '100%'
        },
        mapHeight: {
            type: String,
            default: '100%'
        },
        mapConfig: {
            type: String,
            default: () => {}
        }
    },
    data() {
        return {
            MapKey: '43ad0b3e3da00aae4415289d719aff4a',
            serviceKey: '3aadd3b4716ade055799dca8537fd295',
            MapInfo: {},
            AMapUI: null,
            AMap: null,
            map: null,
            PositionPicker: null,
            geolocatio: null,
            getAmpUIime: null,
            Map: null,
            Geolocation: null,
            Pixel: null,
            event: null
        }
    },
    async mounted() {
        // 已载入高德地图API，则直接初始化地图
        if (window.AMap && window.AMapUI) {
            await this.initMap()
            // 未载入高德地图API，则先载入API再初始化
        } else {
            await remoteLoad(
                `https://webapi.amap.com/maps?v=1.4.4&key=${this.MapKey}`
            ).then(async res => {
                this.getAmpUI()
            })
        }
    },
    methods: {
        deactivated() {
            this.getAmpUIime = null
        },

        async getAmpUI() {
            if (window.AMap.UA) {
                await remoteLoad('https://webapi.amap.com/ui/1.0/main.js')
                await this.initMap()
            } else {
                this.getAmpUIime = setTimeout(() => {
                    this.getAmpUI()
                }, 50)
            }
        },

        async initMap() {
            console.log('初始化地图')
            // 加载PositionPicker，loadUI的路径参数为模块名中 'ui/' 之后的部分
            const AMap = (this.AMap = window.AMap)
            const AMapUI = (this.AMapUI = window.AMapUI)
            this.getAmpUIime = null
            AMapUI.loadUI(['misc/PositionPicker'], PositionPicker => {
                const mapConfig = { ...this.mapConfig }
                const map = (this.map = new AMap.Map(this.$el, mapConfig))
                this.PositionPicker = PositionPicker
                this.$emit('init', this)
            })
        }
    }
}
</script>
